<?php

class yuminew {

    public $var_talk;
    public $conf, $rest_uri;
    public $yuming_website, $yuming_id, $yuming_name;
    public $mobile_url, $web_url;

    public function __construct() {
        $cachefile = DATA . '/cache/config_cache.inc.php';
        if (!is_file($cachefile)) {
            config::update_config();
        }
        $this->conf = require $cachefile;
        $this->conf['ftime'] = filemtime($cachefile);

        $GLOBALS['G'] = $this->conf;

        $uri_info = parse_url($_SERVER['REQUEST_URI']);
        $this->rest_uri = trim($uri_info['path'], '/');
        $httpname = $_SERVER['HTTP_HOST'];

        if (preg_match("#^www\.#", $httpname)) {
            $httpname = substr($httpname, 4);
        }
        if (is_mobile() && IS_MOBILE_SITE) {
            define('IS_MOBILE_SITE', true);
        }
//        if (preg_match("#^m\.#", $httpname)) {
//            define('IS_MOBILE_SITE', true);
//            $httpname = substr($httpname, 2);
//        } else {
//            $mobilename = "m." . $httpname;
//            $this->mobile_url = 'http://' . $mobilename . $_SERVER['REQUEST_URI'];
//        }

        $this->yuming_website = db::find("select * from yuming where name='www.{$httpname}' OR name='{$httpname}'");



        if (!defined('APPNAME') && M != 'catch') {
            if (empty($this->yuming_website)) {
                throw new Exception("Error:没有绑定域名,请登录后台设置");
                exit;
            }

            $GLOBALS['W'] = $this->yuming_website;

            define('IS_MOBILE_SITE_OPEN', $GLOBALS['W']['mobileSwitch'] == 1);

            $this->yuming_id = $this->yuming_website['id'];
            $this->yuming_name = $this->yuming_website['name'];
            $this->web_url = $this->mobile_url = 'http://' . $this->yuming_website['name'] . $_SERVER['REQUEST_URI'];
        }

        // 系统测试
        if ($this->rest_uri == 'systest') {
            echo 'success';
            exit;
        }

        //推送
        if (!empty($GLOBALS['G']['baidu_tui_token']) && rand(0, 20) == 0) {
            $ping = new ping_RPC();
            $result = $ping->ping();
        }
    }

    public static function curlpost($url, $post_data = array(), $signkey = '', $cookiefile = '') {
        $post_data['version'] = $GLOBALS['G']['softversion'];
        return httpUnit::post($url, $post_data, $signkey, $cookiefile);
    }

    

    

    public static function convert_images_url_path($url, $link = '', $yuming_id = '') {
        if ($link) {
            $url = htmlHelper::fix_path($link, $url);
        }
        $img_ext = pathinfo($url, PATHINFO_EXTENSION);
        $md5 = md5($url);
        $md51 = substr($md5, 0, 2);
        $md52 = substr($md5, 2, 2);
        $md53 = substr($md5, 10, 16);
        $hash = $md51 . $md52 . $md53;
        if (in_array($img_ext, array('jpg', 'jpeg', 'png', 'gif'))) {
            $img_ext = "." . $img_ext;
        } elseif ($img_ext == '') {
            $img_ext = ".img";
        } else {
            return "";
        }

        if ($yuming_id) {
            $str_img = "/uploads/{$yuming_id}/" . $md51 . "/" . $md52 . "/" . $md53 . $img_ext;
        } else {
            $str_img = "/uploads/attachment/" . $md51 . "/" . $md52 . "/" . $md53 . $img_ext;
        }

        if (!is_file(ROOT . $str_img)) {
            $imgcon = db::find("select * from attachment where hash='$hash'");
            if (empty($imgcon)) {
                $now_time = time();
                db::query("insert into attachment (hash,url,addtime)
					values ('$hash','$url','$now_time')");
            }
        }
        return $str_img;
    }

    //转换文章内图片地址
    public static function convert_images_patch($body, $alt = '', $link = '', $yuming_id = '') {
        $GLOBALS['catchlink'] = $link;
        $GLOBALS['img_ym_id'] = $yuming_id;
        $body = preg_replace_callback('/src=\"(.*?)\"/is', function($data) {
            $str_img = self::convert_images_url_path($data[1], $GLOBALS['catchlink'], $GLOBALS['img_ym_id']);
            if ($GLOBALS['G']['downPicture'] == 1) {
                if ($str_img) {
                    return "src={$str_img}";
                } else {
                    return "";
                }
            } elseif ($GLOBALS['G']['downPicture'] == 2) {
                return "src=$data[1]";
            } else {
                return "";
            }
        }, $body);
        $body = str_replace('@img#alt@', $alt, $body);
        return $body;
    }

    //接受数组参数
    //同义词替换
    public static function replace_word($body, $yuming_id) {
        $list_rword = db::select("select * from reword where yuming_id='$yuming_id' or yuming_id=0");

        $GLOBALS['protecttag'] = array();
        $body = preg_replace_callback('#<a.*?>.*?</a>|<img.*?>|\[img\].*?\[/img\]|\[url\].*?\[/url\]#is', function($data) {
            $key = substr(md5($data[0]), 10, 16);
            $GLOBALS['protecttag'][$key] = $data[0];
            return '~' . $key . '~';
        }, $body);

        #inline-ignore
        $body = replace_word($list_rword, $body);
        //释放保护
        $body = preg_replace_callback('#~([a-z0-9]{16})~#is', function($data) {
            if (isset($GLOBALS['protecttag'][$data[1]])) {
                return $GLOBALS['protecttag'][$data[1]];
            }
            return $data[0];
        }, $body);
        return $body;
    }

    //关键词优化
    public static function seoword($body, $yuming_id,$words) {
        //print_r($body);
        $r = db::find("select * from seoconfig where yuming_id='$yuming_id'");
        //未设置优化
        if (!$r) {
            return $body;
        }
        $r['seoWordNum'] = intval($r['seoWordNum']);
        //未开启
        if (empty($r['seoWord']) || !$r['seoWordNum']) {
            return $body;
        }
        //伪原创比例
        $ys = crypt::from62(substr(md5($body['title']), 0, 3)) % 100;
        $seoWordScale = intval($r['seoWordScale']);
        if ($seoWordScale < $ys) {
            return $body;
        }
        //取出词语
        $sw_arr = str_replace(array(',', '，'), "\n", $r['seoWord']);
        $sw_arr = explode("\n", $sw_arr);
        foreach ($sw_arr as $k => $value) {
            $sw_arr[$k] = trim($value);
        }
        $sw_arr = array_filter($sw_arr);
        $idx = mt_rand(0, max(0, count($sw_arr) - $r['seoWordNum']));
        $sw_arr = array_slice($sw_arr, $idx, $r['seoWordNum']);

        $seowords = addslashes(join(',', $sw_arr));
        if (!empty($sw_arr)) {
            //插入文章
            $sw_arr_num = count($sw_arr);
            $body_array = explode('，', $body['body']);
            $body_s_count = count($body_array);
            $snum = ceil(($body_s_count / 2) / $sw_arr_num);
            //echo "<br/>";
            #inline-ignore
            foreach ($sw_arr as $key => $value) {
                $k = $snum * $key + 1;
                if (isset($body_array[$k])) {
                    $body_array[$k] = $value . $body_array[$k];
                }
            }
            $body['body'] = join("，", $body_array);
            //插入标题
            if ($r['seoTitle'] == '1') {
                if ($r['seoTitlex'] == '1') {
                    $body['title'] = strip_tags($sw_arr[0]) . $body['title'];
                } elseif ($r['seoTitlex'] == '2') {
                    $body['title'] = $body['title'] . strip_tags($sw_arr[0]);
                } elseif ($r['seoTitlex'] == '3') {
                    $tlen = mb_strlen($body['title'], 'utf-8');
                    $blen = mb_strlen($body['body'], 'utf-8');
                    $sp = $blen % $tlen;
                    $body['title'] = mb_substr($body['title'], 0, $sp, 'utf-8') . strip_tags($sw_arr[0]) . mb_substr($body['title'], $sp, $tlen - $sp, 'utf-8');
                }
            }
            $body['sw_arr'] = $sw_arr;
        }
        return $body;
    }

    // 标题自动优化
    public static function autoseo($title, $yuming_id) {
        $r = db::find("select * from seoconfig where yuming_id='$yuming_id'");
        if (!$r || $r['autoseo'] == 0) {
            return '';
        }
        if ($r['autonum'] > 5 || $r['autonum'] <= 0) {
            $r['autonum'] = 5;
        }
        $title = urlencode($title);
        $data = "";

        $url = "http://tuijian.sogou.com/websearch/features/sohu_recommend.jsp";
        $postdata = "title={$title}&content=1&url=http://sports.sohu.com/20170427/n490895141.shtml";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = urldecode($output);
        $kw = json_decode($output, true);

        if (!empty($kw['hotwords'])) {
            $kw['hotwords'] = array_slice($kw['hotwords'], 0, $r['autonum']);
            $word = addslashes(implode('_', $kw['hotwords']));
        }
        return $word;
    }

    //随机得到关键词库中的几个关键词
    public static function get_words_lists($num, $yuming_id) {
        $data = db::select("SELECT * FROM `words_{$yuming_id}` AS t1 JOIN (SELECT ROUND(RAND() * (
            (SELECT MAX(id) FROM `words_{$yuming_id}`)-(SELECT MIN(id) FROM `words_{$yuming_id}`))+(SELECT MIN(id) FROM `words_{$yuming_id}`)) AS id) AS t2
            WHERE t1.id >= t2.id
            ORDER BY t1.id LIMIT {$num};"
        );
        $result = [];
        foreach($data as $v) {
            $result[] = $v['title'];
        }
        return $result;
    }

}
